//
//  DFBaseLineCell.m
//  DFTimelineView
//
//  Created by Allen Zhong on 15/9/27.
//  Copyright (c) 2015年 Datafans, Inc. All rights reserved.
//





#define UserNickFont [UIFont systemFontOfSize:16]
#define TitleLabelFont [UIFont systemFontOfSize:13]

#define LocationLabelFont [UIFont systemFontOfSize:10]

#define TimeLabelFont [UIFont systemFontOfSize:12]

//#define UserNickLabelHeight 15
#define UserNickMaxWidth 150

#define LocationLabelHeight 15

#define TimeLabelHeight 15

#define UserNickLineHeight 1.0f


#define LikeLabelFont [UIFont systemFontOfSize:14]

#define LikeLabelLineHeight 1.1f

#define LikeCommentTimeSpace 3

#define ToolbarWidth 150
#define ToolbarHeight 30

#import "DFBaseLineCell.h"
#import "MLLabel+Size.h"
#import "DFLikeCommentView.h"
#import "DFLikeCommentToolbar.h"
#import "DFToolUtil.h"


@interface DFBaseLineCell()<DFLikeCommentToolbarDelegate, DFLikeCommentViewDelegate>{

    NSInteger type;

}

@property (nonatomic, strong) DFBaseLineItem *item;

@property (nonatomic, strong) UIImageView *userAvatarView;
@property (nonatomic, strong) UIButton *userAvatarButton;

@property (nonatomic, strong) MLLinkLabel *userNickLabel;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UIView * lineview;

@property (nonatomic, strong) UILabel *locationLabel;

@property (nonatomic, strong) UILabel *timeLabel;

@property (nonatomic, strong) UIButton *likeCmtButton;



@property (nonatomic, strong) DFLikeCommentView *likeCommentView;


@property (nonatomic, strong) DFLikeCommentToolbar *likeCommentToolbar;


@property (nonatomic, assign) BOOL isLikeCommentToolbarShow;

@end



@implementation DFBaseLineCell


#pragma mark - Lifecycle
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        _isLikeCommentToolbarShow = NO;
        
        [self initBaseCell];
    }
    return self;
}

-(void) initBaseCell
{
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    CGFloat x = 0.0, y, width, height;
    
    if (_userAvatarView == nil ) {
        
        x = Margin;
        y = Margin;
        width = UserAvatarSize;
        height = width;
        _userAvatarView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
//        [_userAvatarView.layer setCornerRadius:(_userAvatarView.frame.size.height/2)];
//        [_userAvatarView.layer setMasksToBounds:YES];
//        [_userAvatarView setContentMode:UIViewContentModeScaleAspectFill];
        [_userAvatarView setClipsToBounds:YES];
        _userAvatarView.layer.shadowColor = [UIColor whiteColor].CGColor;
//        _userAvatarView.layer.shadowOffset = CGSizeMake(4, 4);
//        _userAvatarView.layer.shadowOpacity = 0.5;
//        _userAvatarView.layer.shadowRadius = 2.0;
        _userAvatarView.layer.masksToBounds = YES;
        _userAvatarView.layer.cornerRadius = 8.0f;
        _userAvatarView.backgroundColor = [UIColor lightGrayColor];
        [self.contentView addSubview:_userAvatarView];
        
        _userAvatarButton = [[UIButton alloc] initWithFrame:_userAvatarView.frame];
        [_userAvatarButton addTarget:self action:@selector(onClickUserAvatar:) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:_userAvatarButton];
    }
    
    if (_userNickLabel == nil) {
        
        _userNickLabel =[[MLLinkLabel alloc] initWithFrame:CGRectZero];
        _userNickLabel.textColor = HighLightTextColor;
        _userNickLabel.font = UserNickFont;
        _userNickLabel.numberOfLines = 1;
        _userNickLabel.adjustsFontSizeToFitWidth = NO;
        _userNickLabel.textInsets = UIEdgeInsetsZero;
        
        _userNickLabel.dataDetectorTypes = MLDataDetectorTypeAll;
        _userNickLabel.allowLineBreakInsideLinks = NO;
        _userNickLabel.linkTextAttributes = nil;
        _userNickLabel.activeLinkTextAttributes = nil;
        _userNickLabel.lineHeightMultiple = UserNickLineHeight;
        [self.contentView addSubview:_userNickLabel];
    }
    
    if (_titleLabel == nil) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _titleLabel.textColor = [UIColor lightGrayColor];
        _titleLabel.font = TitleLabelFont;
        [self.contentView addSubview:_titleLabel];
    }
    
    if (_bodyView == nil) {
        x = CGRectGetMaxX(_userAvatarView.frame) + Margin;
        y = 40;
        width = BodyMaxWidth;
//        width = screenW;
        height = 1;
        _bodyView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
        [self.contentView addSubview:_bodyView];
    }
    
    
    
    if (_locationLabel == nil) {
        _locationLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _locationLabel.textColor = [UIColor colorWithRed:35/255.0 green:83/255.0 blue:120/255.0 alpha:1.0];
        _locationLabel.font = LocationLabelFont;
        _locationLabel.hidden = YES;
//        [self.contentView addSubview:_locationLabel];
    }
    
    
    
    if (_timeLabel == nil) {
        _timeLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _timeLabel.textColor = [UIColor lightGrayColor];
        _timeLabel.font = TimeLabelFont;
        _timeLabel.hidden = YES;
        _timeLabel.textAlignment = NSTextAlignmentRight;
        [self.contentView addSubview:_timeLabel];
    }
    
    
    if (_likeCmtButton == nil) {
        _likeCmtButton = [[UIButton alloc] initWithFrame:CGRectZero];
        _likeCmtButton.hidden = YES;
        [_likeCmtButton setImage:[UIImage imageNamed:@"AlbumOperateMore"] forState:UIControlStateNormal];
        [_likeCmtButton setImage:[UIImage imageNamed:@"AlbumOperateMoreHL"] forState:UIControlStateHighlighted];
        [_likeCmtButton addTarget:self action:@selector(onClickLikeCommentBtn:) forControlEvents:UIControlEventTouchUpInside];
//        [self.contentView addSubview:_likeCmtButton];
    }
    
    
    if (_likeCommentView == nil) {
        y = 0;
        width = BodyMaxWidth;
        height = 10;
        _likeCommentView = [[DFLikeCommentView alloc] initWithFrame:CGRectMake(x, y, width, height)];
        _likeCommentView.delegate = self;
//        [self.contentView addSubview:_likeCommentView];  
    }

    
    
    if (_likeCommentToolbar == nil) {
        y = 0;
        x = 0;
        width = ToolbarWidth;
        height = ToolbarHeight;
        _likeCommentToolbar = [[DFLikeCommentToolbar alloc] initWithFrame:CGRectMake(x, y, width, height)];
        _likeCommentToolbar.delegate = self;
        _likeCommentToolbar.hidden = YES;
//        [self.contentView addSubview:_likeCommentToolbar];
    }
    
    _lineview = [[UIView alloc]init];
    _lineview.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1];
    
    self.userCommentBtn = [[UIButton alloc] init];
    [self.userCommentBtn addTarget:self action:@selector(onClickCot:) forControlEvents:UIControlEventTouchUpInside];
    
    self.shareBtn = [[UIButton alloc]init];
    [self.shareBtn setImage:[UIImage imageNamed:@"商务圈-分享"] forState:0];
    [self.shareBtn addTarget:self action:@selector(onClickShare:) forControlEvents:UIControlEventTouchUpInside];
    
    self.zanBtn = [[UIButton alloc]init];
    [self.zanBtn setImage:[UIImage imageNamed:@"商务圈-点赞"] forState:0];
//    [self.zanBtn setImage:[UIImage imageNamed:@"点赞c"] forState:UIControlStateSelected];
    [self.zanBtn addTarget:self action:@selector(onClickZan:) forControlEvents:UIControlEventTouchUpInside];
    
    self.commentBtn = [[UIButton alloc]init];
    [self.commentBtn setImage:[UIImage imageNamed:@"商务圈-评论"] forState:0];
    [self.commentBtn addTarget:self action:@selector(onClickCot:) forControlEvents:UIControlEventTouchUpInside];
    
    self.shareLabel = [[UILabel alloc]init];
    self.shareLabel.font = [UIFont fontWithName:@"CourierNewPSMT" size:12];
    self.shareLabel.textColor = [UIColor lightGrayColor];
    self.shareLabel.text = @"0";
    
    self.zanLabel = [[UILabel alloc]init];
    self.zanLabel.font = [UIFont fontWithName:@"CourierNewPSMT" size:12];
    self.zanLabel.textColor = [UIColor lightGrayColor];
    self.zanLabel.text = @"0";
    
    self.commentLabel = [[UILabel alloc]init];
    self.commentLabel.font = [UIFont fontWithName:@"CourierNewPSMT" size:12];
    self.commentLabel.text = @"0";
    
    self.companyName = [[UILabel alloc]init];
    self.companyName.font = [UIFont systemFontOfSize:12];
    self.companyName.textColor = [UIColor lightGrayColor];
    
    self.vImg = [[UIImageView alloc]init];
    self.authState = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"认证"]];
    
    if (screenW < 600) {
        
//        [self.contentView addSubview:self.shareLabel];
        [self.contentView addSubview:self.zanLabel];
        [self.contentView addSubview:self.commentLabel];
//        [self.contentView addSubview:self.shareBtn];
        [self.contentView addSubview:self.zanBtn];
        [self.contentView addSubview:self.commentBtn];
//        [self.contentView addSubview:_lineview];
        
        [self.contentView addSubview:self.userCommentBtn];
        [self.contentView addSubview:self.vImg];
        [self.contentView addSubview:self.authState];
  
    }
}




#pragma mark - Method

-(void)updateWithItem:(DFBaseLineItem *)item
{
    self.item = item;
    
    
    [_userAvatarView sd_setImageWithURL:[NSURL URLWithString:item.userAvatar]];
    
    NSAttributedString *userNick  = [[NSAttributedString alloc] initWithString:item.userNick];
    
    CGSize textSize = [MLLinkLabel getViewSize:userNick maxWidth:UserNickMaxWidth font:UserNickFont lineHeight:UserNickLineHeight lines:1];
    
    CGFloat x, y, width, height;
    x = CGRectGetMaxX(_userAvatarView.frame) + 15;
    y = CGRectGetMinY(_userAvatarView.frame) +2;
    width = textSize.width;
    height = textSize.height;
    
    _userNickLabel.frame = CGRectMake(x, y, width, height);
    _userNickLabel.attributedText = userNick;
    
    
    x = CGRectGetMaxX(_userNickLabel.frame) + Padding;
    width = [UIScreen mainScreen].bounds.size.width - x - Margin;
//    _titleLabel.frame = CGRectMake(x - 8, y, width, height);
        _titleLabel.frame = CGRectMake(x, y, width, height);
    _titleLabel.text = item.title;
    _titleLabel.hidden = item.title == nil || [item.title isEqualToString:@""];
}


-(void)updateBodyView:(CGFloat) height
{
    CGFloat x, y, width;
    x = _bodyView.frame.origin.x;
    y = _bodyView.frame.origin.y;
    width = _bodyView.frame.size.width;
    height = height;
    _bodyView.frame = CGRectMake(x, y, width, height);
    
//     _bodyView.frame = CGRectMake( _userAvatarView.x,  _userAvatarView.height + 15, screenW, height);
    [self updateLocationLikeComment:height];
    
}


-(void) updateLocationLikeComment:(CGFloat)height
{
    
    CGFloat x, y, width, sumHeight=0.0;
    
    x = _bodyView.frame.origin.x;
    y = _bodyView.frame.origin.y;
    width = _bodyView.frame.size.width;
    
    //位置
    if (self.item.location != nil && ![self.item.location isEqualToString:@""]) {
        y = CGRectGetMaxY(_bodyView.frame) + Padding;
        height = LocationLabelHeight;
        _locationLabel.hidden = NO;
        _locationLabel.frame = CGRectMake(x, y, width, height);
        _locationLabel.text = self.item.location;
        
        sumHeight+=LocationLabelHeight+Padding;
        
    }else{
        _locationLabel.hidden = YES;
    }
    
    self.userCommentBtn.frame = CGRectMake(60, y-40, screenW - 60, 40);
    
    _lineview.frame = CGRectMake(10, _bodyView.y + _bodyView.height + 25, self.width - 20, 1);
    
    self.authState.frame = CGRectMake(_userAvatarView.width + 2, _userAvatarView.height + _userAvatarView.y-15, 14, 17);
    
//    self.shareBtn.frame = CGRectMake(_bodyView.width/2 + 30, _bodyView.height + _bodyView.y + 8, 30, 20);
    
    self.zanBtn.frame = CGRectMake(_bodyView.width - 20, _bodyView.height + _bodyView.y + 8, 30, 20);
    
    self.commentBtn.frame = CGRectMake(self.width - 60, _bodyView.height + _bodyView.y + 9, 30, 20);
    
//    self.shareLabel.frame = CGRectMake(self.shareBtn.x + self.shareBtn.width + 4, self.shareBtn.y, 30, 20);
//    self.shareLabel.text = self.item.shareCount;
    
    self.zanLabel.frame = CGRectMake(self.zanBtn.x + self.zanBtn.width + 2, self.zanBtn.y + 1, 30, 20);
    self.zanLabel.text = self.item.zanCount;
    
    self.commentLabel.frame = CGRectMake(self.commentBtn.x + self.commentBtn.width + 2, self.commentBtn.y , 30, 20);
    self.commentLabel.text = self.item.commentCount;
    
    self.companyName.frame = CGRectMake(_userNickLabel.x, _userNickLabel.y + _userNickLabel.height + 2, screenW - _userAvatarView.width - 50, 20);
    self.companyName.text = self.item.companyName;
    
    self.vImg.frame = CGRectMake(_titleLabel.x + (_titleLabel.text.length *14), _titleLabel.y + 2, 15, 15);
    
    //时间
//    y = CGRectGetMaxY(_bodyView.frame) + sumHeight + Padding;
    y = Margin + 5;
    width = 100;
    height = TimeLabelHeight;
    _timeLabel.hidden = NO;
    _timeLabel.frame = CGRectMake(screenW - 120, y, width, height);

    _timeLabel.text = [CustomExcetion prettyDateWithReference:[CustomExcetion dateFromString:self.item.ts]];

    NSString * str = [CustomExcetion prettyDateWithReference:[CustomExcetion dateFromString:self.item.ts]];
    _timeLabel.text = str;

    //点赞评论按钮
    width = 25;
    height = 25;
    x = CGRectGetMaxX(_bodyView.frame) - width;
    _likeCmtButton.hidden = NO;
    _likeCmtButton.frame = CGRectMake(x+2, y-7, width, height);
    
    
    //点赞和评论Toolbar
    width = _likeCommentToolbar.frame.size.width;
    height = _likeCommentToolbar.frame.size.height;
    x = CGRectGetMinX(_likeCmtButton.frame) - width - 10;
    y = CGRectGetMinY(_likeCmtButton.frame) - 1;
    _likeCommentToolbar.frame = CGRectMake(x, y, width, height);
    
    //点赞和评论
    if (self.item.likes.count ==0 && self.item.comments.count == 0) {
        
        _likeCommentView.hidden = YES;
    }else{
        _likeCommentView.hidden = NO;
        
        x = CGRectGetMinX(_timeLabel.frame);
        y = CGRectGetMaxY(_timeLabel.frame)+LikeCommentTimeSpace;
        width = _likeCommentView.frame.size.width;
        height = [DFLikeCommentView getHeight:self.item maxWidth:BodyMaxWidth];
        _likeCommentView.frame = CGRectMake(x, y, width, height);
        [_likeCommentView updateWithItem:self.item];
    }

   
//    if ([self.item.authState isEqualToString:@"2"]) {
//        
//        self.vImg.image = [UIImage imageNamed:@"yirenzheng"];
//        
//    }else{
//    
//        self.vImg.image = [UIImage imageNamed:@"weirenzheng"];
//    
//    }
    self.authState.hidden = [UsedTool authStateImageViewHidden:self.item.isAuthState];
    self.vImg.image = [UsedTool setVipimage:self.item.authState];
    
    if ([self.item.isZan isEqualToString:@"是"]) {
        
        self.zanLabel.textColor = [UIColor orangeColor];
        self.zanBtn.selected = YES;
        
    }else{
    
        self.zanLabel.textColor = [UIColor blackColor];
        self.zanBtn.selected = NO;
    
    }
}

+(CGFloat)getCellHeight:(DFBaseLineItem *)item
{
    //基本
    CGFloat height = Margin + UserAvatarSize;
    
    //位置
    if (item.location != nil && ![item.location isEqualToString:@""]) {
        height+=LocationLabelHeight+Padding;
    }

    //时间
    height+= TimeLabelHeight + Padding;
    
    //点赞和评论
    if (!(item.likes.count == 0 && item.comments.count == 0)) {
        height+=[DFLikeCommentView getHeight:item maxWidth:BodyMaxWidth]+LikeCommentTimeSpace;
    }

    
    return height;
}

-(void) onClickUserAvatar:(id)sender
{
    if (_delegate != nil && [_delegate respondsToSelector:@selector(onClickUser:userType:)]) {
        [_delegate onClickUser:self.item.userId userType:self.item.userType];
    }
}

-(void) onClickShare:(id)sender{

    if (_delegate != nil && [_delegate respondsToSelector:@selector(onClickUserShare:)]) {
        [_delegate onClickUserShare:self.item.userId];
    }

}

-(void) onClickZan:(id)sender{
    
    if (allConstMemberid) {
        
        if (_delegate != nil && [_delegate respondsToSelector:@selector(onClickUserZan:)]) {
            
            self.zanBtn.selected = !self.zanBtn.selected;
            
            if (self.zanBtn.selected) {
                
                self.zanLabel.textColor = [UIColor orangeColor];
                type = 1;
                [self zanSendRequest];
                self.item.isZan = @"是";
                NSInteger count = [self.zanLabel.text integerValue] + 1;
                self.zanLabel.text = [NSString stringWithFormat:@"%ld",(long)count];
                self.item.zanCount = [NSString stringWithFormat:@"%ld",(long)count];
                
            }else{
                
                self.zanLabel.textColor = [UIColor blackColor];
                type = 2;
                [self zanSendRequest];
                self.item.isZan = @"否";
                NSInteger count = [self.zanLabel.text integerValue] - 1;
                self.zanLabel.text = [NSString stringWithFormat:@"%ld",(long)count];
                self.item.zanCount = [NSString stringWithFormat:@"%ld",(long)count];
                
            }
            
            [_delegate onClickUserZan:self.item.userId];
        }
        

    }else{
    
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        [alert show];
    
    }
    
    
}

#pragma mark - alertview
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        //登录
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
        [[self viewController] presentViewController:loginNAV animated:YES completion:nil];
    }
    
    
}
- (UIViewController *)viewController
{
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

-(void) onClickCot:(id)sender{
    
    if (_delegate != nil && [_delegate respondsToSelector:@selector(onClickUserCot:userResid:)]) {
        [_delegate onClickUserCot:self.item.userId userResid:self.item.resId];
    }
    
}
-(void) onClickLikeCommentBtn:(id)sender
{
    _isLikeCommentToolbarShow = !_isLikeCommentToolbarShow;
    _likeCommentToolbar.hidden = !_isLikeCommentToolbarShow;
}

-(void)zanSendRequest{

    
    NSMutableDictionary * dic = [NSMutableDictionary  dictionary];
    dic[@"userId"] = allConstMemberid;
    dic[@"token"] = allConstMemberToken;
    dic[@"resId"] = self.item.resId;
    dic[@"type"] = @(type);
    
    [LSHttpTool sendHttpData:@"zanCibd_app_cibd.im.lensum" params:dic success:^(id responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {

            [self showRightWithTitle:dicInfo[@"msg"] autoCloseTime:2];
            
        }else{

            [self showSingleIconBubble:dicInfo[@"msg"]];
        }
        
    } failure:^(NSError *error) {

        [self showSingleIconBubble:@"网络连接错误"];
        
    }];


}

-(void)hideLikeCommentToolbar
{
    if (_isLikeCommentToolbarShow == NO) {
        return;
    }
    _isLikeCommentToolbarShow = NO;
    _likeCommentToolbar.hidden = YES;
}


#pragma mark - DFLikeCommentToolbarDelegate

-(void)onLike
{
   
    [self hideLikeCommentToolbar];
    
    if (_delegate != nil && [_delegate respondsToSelector:@selector(onLike:)]) {
        [_delegate onLike:self.item.itemId];
    }
}


-(void)onComment
{
    
    [self hideLikeCommentToolbar];
    
    if (_delegate != nil && [_delegate respondsToSelector:@selector(onComment:)]) {
        [_delegate onComment:self.item.itemId];
    }
}



#pragma mark - DFLikeCommentViewDelegate

-(void)onClickUser:(NSUInteger)userId userType:(NSString *)userType
{
    if (_delegate != nil && [_delegate respondsToSelector:@selector(onClickUser:)]) {
        [_delegate onClickUser:self.item.userId userType:self.item.userType];
    }

}

-(void)onClickUserShare:(NSUInteger)userId
{
    if (_delegate != nil && [_delegate respondsToSelector:@selector(onClickUserShare:)]) {
        [_delegate onClickUserShare:userId];
    }
    
}

-(void)onClickUserZan:(NSUInteger)userId
{
    if (_delegate != nil && [_delegate respondsToSelector:@selector(onClickUserZan:)]) {
        [_delegate onClickUserZan:userId];
    }
    
}

-(void)onClickUserCot:(NSUInteger)userId userResid:(NSString *)userResid
{
    if (_delegate != nil && [_delegate respondsToSelector:@selector(onClickCot:)]) {
        [_delegate onClickUserCot:self.item.userId userResid:self.item.resId];
    }
    
}
-(void)onClickComment:(long long)commentId
{
    if (_delegate != nil && [_delegate respondsToSelector:@selector(onClickComment:itemId:)]) {
        [_delegate onClickComment:commentId itemId:self.item.itemId];
    }
}
@end
